#!/usr/bin/env python3
"""
简化版的修复脚本，在正确的环境下运行
"""

import os
import sys
import uuid

# 添加API目录到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'api'))

from sqlalchemy.orm import Session
from api.app.database import SessionLocal
from api.app.models import App, User, Memory, MemoryAccessLog


def list_user_apps(user_id: str):
    """列出用户的所有应用"""
    db = SessionLocal()
    try:
        user = db.query(User).filter(User.user_id == user_id).first()
        if not user:
            print(f"❌ 用户 {user_id} 不存在")
            return []
        
        apps = db.query(App).filter(App.owner_id == user.id).order_by(App.created_at).all()
        
        print(f"\n📋 用户 {user_id} 的所有应用:")
        print("=" * 100)
        for i, app in enumerate(apps, 1):
            memory_count = db.query(Memory).filter(Memory.app_id == app.id).count()
            access_count = db.query(MemoryAccessLog).filter(MemoryAccessLog.app_id == app.id).count()
            print(f"{i:2d}. ID: {app.id}")
            print(f"    名称: '{app.name}'")
            print(f"    记忆数: {memory_count}")
            print(f"    访问数: {access_count}")
            print(f"    状态: {'🟢 活跃' if app.is_active else '🔴 暂停'}")
            print(f"    创建时间: {app.created_at}")
            print("-" * 50)
        
        return apps
    finally:
        db.close()


def find_similar_apps(user_id: str, target_name: str = "OpenMemory"):
    """查找相似名称的应用"""
    db = SessionLocal()
    try:
        user = db.query(User).filter(User.user_id == user_id).first()
        if not user:
            return []
        
        # 查找包含目标名称的应用（不区分大小写）
        apps = db.query(App).filter(
            App.owner_id == user.id,
            App.name.ilike(f"%{target_name}%")
        ).all()
        
        return apps
    finally:
        db.close()


def merge_apps_by_name(user_id: str, target_name: str = "OpenMemory"):
    """合并同名应用"""
    db = SessionLocal()
    try:
        user = db.query(User).filter(User.user_id == user_id).first()
        if not user:
            print("❌ 用户不存在")
            return False
        
        # 查找目标名称的应用
        apps = db.query(App).filter(
            App.owner_id == user.id,
            App.name.ilike(f"%{target_name}%")
        ).order_by(App.created_at).all()
        
        if len(apps) <= 1:
            print(f"✅ 没有找到需要合并的 '{target_name}' 应用")
            return True
        
        print(f"🔍 发现 {len(apps)} 个相关应用")
        
        # 保留第一个创建的应用
        keep_app = apps[0]
        merge_apps = apps[1:]
        
        print(f"📌 将保留: {keep_app.name} (ID: {keep_app.id})")
        print(f"📤 将合并: {[f'{app.name} ({app.id})' for app in merge_apps]}")
        
        total_memories_moved = 0
        total_logs_moved = 0
        
        for merge_app in merge_apps:
            # 更新记忆关联
            memories = db.query(Memory).filter(Memory.app_id == merge_app.id).all()
            for memory in memories:
                memory.app_id = keep_app.id
                total_memories_moved += 1
            
            # 更新访问日志关联
            logs = db.query(MemoryAccessLog).filter(MemoryAccessLog.app_id == merge_app.id).all()
            for log in logs:
                log.app_id = keep_app.id
                total_logs_moved += 1
            
            # 删除合并的应用
            db.delete(merge_app)
            
            print(f"   ✅ 合并 {merge_app.name}: {len(memories)} 条记忆, {len(logs)} 条日志")
        
        # 标准化保留应用的名称
        if keep_app.name.lower() != target_name.lower():
            keep_app.name = target_name
            print(f"   📝 标准化应用名称: {keep_app.name}")
        
        db.commit()
        
        print(f"\n🎉 合并完成!")
        print(f"   保留应用: {keep_app.name} ({keep_app.id})")
        print(f"   合并记忆: {total_memories_moved} 条")
        print(f"   合并日志: {total_logs_moved} 条")
        
        return True
        
    except Exception as e:
        db.rollback()
        print(f"❌ 合并过程中出错: {e}")
        import traceback
        traceback.print_exc()
        return False
    finally:
        db.close()


def main():
    """主函数"""
    user_id = "default_user"
    target_name = "OpenMemory"
    
    print("🚀 OpenMemory 重复应用修复工具")
    print("=" * 50)
    
    # 列出所有应用
    apps = list_user_apps(user_id)
    
    if not apps:
        print("❌ 没有找到任何应用")
        return
    
    # 查找相关应用
    similar_apps = find_similar_apps(user_id, target_name)
    
    if similar_apps:
        print(f"\n🔍 找到 {len(similar_apps)} 个相关应用:")
        for app in similar_apps:
            print(f"   - '{app.name}' ({app.id})")
        
        # 确认合并
        confirm = input(f"\n❓ 是否合并这些应用到 '{target_name}'? (y/N): ").strip().lower()
        if confirm == 'y':
            merge_apps_by_name(user_id, target_name)
        else:
            print("❌ 取消合并")
    else:
        print(f"\n✅ 没有找到需要合并的 '{target_name}' 应用")
    
    # 再次列出应用确认
    print("\n📊 修复后的应用列表:")
    list_user_apps(user_id)


if __name__ == "__main__":
    main()